package com.xinlianshiye.im.controller;

import com.xinlianshiye.im.ResponseBody;
import com.xinlianshiye.im.Result;
import com.xinlianshiye.im.bean.Record;
import com.xinlianshiye.im.response.Page;
import com.xinlianshiye.im.response.RecordViews;
import com.xinlianshiye.im.service.RecordService;
import com.xinlianshiye.im.service.UserService;
import com.xinlianshiye.im.utils.RedisReceiver;
import com.xinlianshiye.im.utils.SessionManager;
import com.xinlianshiye.im.websocket.WebSocketController;
import com.xinlianshiye.im.websocket.WebSocketRequestMapping;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.Session;
import java.sql.Date;
import java.time.Instant;
import java.time.LocalDate;
import java.util.stream.Collectors;

@Slf4j
@WebSocketController
@RestController
@RequestMapping("im/record")
public class IMRecordController {

    @Autowired
    private UserService userService;
    @Autowired
    private RecordService recordService;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private RedisReceiver redisReceiver;

    @PostMapping("send")
    public void send(String sessionId, Integer userId, Boolean haveRead, Boolean isSender, Integer type, String content) {
        Session session = sessionManager.getSessionById(sessionId);
        Integer receiverId = userService.getUserId(session);
        Record record = new Record();
        record.setOwnerId(userId);
        record.setOtherId(receiverId);
        record.setHaveRead(haveRead);
        record.setSender(isSender);
        record.setCreateTime(Instant.now());
        record.setDeleted(false);
        record.setType(type);
        record.setContent(content);
        redisReceiver.send(session, ResponseBody.initChat(userId, receiverId, record));
    }

    /**
     * 历史好友聊天记录
     */
    @WebSocketRequestMapping("userRecordPage")
    public Result userRecordPage(@RequestParam Integer toId, Integer start, @RequestParam Integer limit, String starttime, String slursearch, Session session) {
        LocalDate startTime = null;
        if (starttime != null) {
            startTime = LocalDate.parse(starttime);
        }
        return Result.success(recordService.page4PC(userService.getUserId(session), toId, start, limit, slursearch, startTime));
    }

    /**
     * 关闭聊天信息
     */
    @WebSocketRequestMapping("delMsgListInfo")
    public Result delMsgListInfo(@RequestParam Integer recordid, Session session) {
        Record record = recordService.getOrElseThrow(recordid);
        recordService.delete(record.getOwnerId(), record.getOtherId());
        return Result.success(true);
    }

    /**
     * 修改信息内容为已读
     */
    @WebSocketRequestMapping("UserIdRecord")
    public Result UserIdRecord(@RequestParam Integer toId, Session session) {
        recordService.read(toId, userService.getUserId(session));
        return Result.success(null);
    }

    /**
     * 获取当前聊天对象的未读取的消息 并修改成已读状态
     */
    @WebSocketRequestMapping("findUserRead")
    public Result findUserRead(@RequestParam Integer toId, Session session) {
        return Result.success(recordService.listUnRead(userService.getUserId(session), toId));
    }

    /**
     * 当前好友聊天记录
     */
    @WebSocketRequestMapping("pageNowRecord")
    public Result pageNowRecord(@RequestParam Integer toId, Integer start, @RequestParam Integer limit, Session session) {
        Page<Record> page = recordService.page4APP(userService.getUserId(session), toId, start, limit);
        return Result.success(new Page<>(page.getItems().stream().map(record -> {
            RecordViews rd = new RecordViews();
            rd.setId(record.getId());
            rd.setDate(Date.from(record.getCreateTime()));
            rd.setIssend(record.isSender());
            rd.setType(record.getType());
            rd.setState(record.getHaveRead());
            rd.setContent(record.getContent());
            rd.setFromId(record.getOwnerId());
            rd.setToId(record.getOtherId());
            return rd;
        }).collect(Collectors.toList()), page.getStart(), page.getLimit(), page.getTotalCount(), page.getBool()));
    }
}
